package leetcode_1423

/**
 * 解题思路，使用滑动窗口求出最小值，即为取出牌的最大值
 */
func maxScore(cardPoints []int, k int) int {
	sum, sliceSum, length := 0, 0, len(cardPoints)

	// 统计出整个数组的大小
	for i := 0; i < length; i++ {
		if i < length-k {
			sliceSum += cardPoints[i]
		}
		sum += cardPoints[i]
	}

	// 统计出（length-k）滑动窗口的最小值
	min := sliceSum
	for left, right := 0, length-k-1; right < length-1; {
		sliceSum = sliceSum - cardPoints[left] + cardPoints[right+1]
		if min > sliceSum {
			min = sliceSum
		}

		left++
		right++
	}

	return sum - min
}

/**
 * 分析左右两侧的取值，类似于滑动窗口
 */
func maxScore2(cardPoints []int, k int) int {
	sliceSum, length := 0, len(cardPoints)

	// 统计前k个元素的大小
	for i := 0; i < k; i++ {
		sliceSum += cardPoints[i]
	}

	// 从左侧取出数字放入右侧
	maxSum := sliceSum
	for left, right := k-1, length-1; left >= 0; {
		sliceSum = sliceSum - cardPoints[left] + cardPoints[right]
		if maxSum < sliceSum {
			maxSum = sliceSum
		}

		left--
		right--
	}

	return maxSum
}
